/**
 * Class for working with preferences
 */
var Preferences = (function(){
    var preferences = {
        url: undefined,
        info: undefined,
        update: undefined,
    };
    
    /**
     * Initialisation
     * 
     * This methods initialisate the preferences.
     * On fist run it initialize the default values
     */
    function init() {
        loadPreferences();
        if ( !preferences.info ) {
            // First run
            preferences.url = '';
            preferences.info = ['cpu', 'mem', 'tx', 'rx'];
            preferences.update = '10';
            public.savePreferences();
        }
    }; // end of function init()

    /**
     * Loading preferences
     */
    function loadPreferences() {
        preferences.url = widget.preferences.getItem('url');
        preferences.info = widget.preferences.getItem('info');
        preferences.update = widget.preferences.getItem('update');
    }; // end of function loadPreferences()
    

    var public = {
        /**
         * Saving preferences
         */
        savePreferences: function() {
            widget.preferences.setItem('url', preferences.url);
            widget.preferences.setItem('info', preferences.info);
            widget.preferences.setItem('update', preferences.update);
        }, // end of function readUrl()

        /**
         * Setting form field values according to preferences
         */
        setFormFields: function() {
            $('input[name="url"]').val(preferences.url);
            $('input[name="info[]"]').each(function() {
                this.checked = preferences.info.indexOf(this.value) != -1;
            });
            $('input[name="update"]').each(function() {
                this.checked = this.value == preferences.update;
            });
        }, // end of function setFormFields()

        /**
        * Reading preferences from form fields
        */
        readFormFields: function() {
            preferences.url = $('input[name="url"]').val();
            preferences.info = [];
            $('input[name="info[]"]').each(function(){
                if ( this.checked ) {
                    preferences.info.push(this.value);
                }
            });
            $('input[name="update"]').each(function() {
                if ( this.checked ) {
                    preferences.update = this.value;
                }
            });
        } // end of function readFormFields();
    };

    init();
    return public;
}());